package org.edu.modules.oa.controller;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.github.xiaoymin.knife4j.annotations.ApiSort;
import groovy.util.logging.Slf4j;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.poi.ss.formula.functions.T;
import org.apache.shiro.SecurityUtils;
import org.edu.common.api.vo.Result;
import org.edu.common.aspect.annotation.AutoLog;
import org.edu.common.system.vo.LoginUser;
import org.edu.common.util.RedisUtil;
import org.edu.modules.oa.config.QueryConditionTool;
import org.edu.modules.oa.entity.VeOaCarInfoEntity;
import org.edu.modules.oa.entity.VeOaCarJiayouEntity;
import org.edu.modules.oa.service.IVeOaCarInfoService;
import org.edu.modules.oa.service.IVeOaCarJiayouService;
import org.edu.modules.oa.util.OssDownloadUtil;
import org.edu.modules.oa.vo.*;
import org.jeecgframework.poi.excel.ExcelImportUtil;
import org.jeecgframework.poi.excel.def.NormalExcelConstants;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.entity.ImportParams;
import org.jeecgframework.poi.excel.view.JeecgEntityExcelView;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

@Api(tags="车辆加油记录")
@RestController
@RequestMapping("oa/veOaCarJiayou")
@Slf4j
@ApiSort(value = 100)

public class VeOaCarJiayouController {

    @Autowired
    private RedisUtil redisUtil; // redis服务类
    @Resource()
    private IVeOaCarJiayouService iVeOaCarJiayouService;// 加油业务类

    @Resource()
    private IVeOaCarInfoService iVeOaCarInfoService;// 车辆信息业务类

@AutoLog(value = "车辆加油记录-显示表格")

    @ApiOperation(value="显示表格", notes="车辆加油记录-显示表格")

    @PostMapping(value = "/showTable")

    public Result<?> showTable(VeOaCarJiayouTableVo veOaCarJiayouTableVo, Integer startPage, Integer pageSize) {
        HashMap<String, Object> map=iVeOaCarJiayouService.showTable(veOaCarJiayouTableVo,startPage,pageSize);
    // 获取redis存的用户值

    LoginUser user = (LoginUser) SecurityUtils.getSubject().getPrincipal();

    map.put("userName",user.getRealname());
        return Result.OK(map);
    }
    @AutoLog(value = "车辆加油记录-单个删除")
    @ApiOperation(value="单个删除", notes="车辆加油记录-单个删除")
    @PostMapping(value = "/oneDelete")

    public Result<?> oneDelete(Integer id) {
        Integer result=iVeOaCarJiayouService.deleteRecord(id);
        return Result.OK();
    }
    @AutoLog(value = "车辆加油记录-批量删除")
    @ApiOperation(value="批量删除", notes="车辆加油记录-批量删除")
    @PostMapping(value = "/allDelete")

    public Result<?> allDelete(String idStr) {
        Integer result=0;
      String data[] = idStr.split(",");

      for (int i=1;i<data.length;i++){

          result+=iVeOaCarJiayouService.deleteRecord(Integer.valueOf(data[i]));

      }
        return Result.OK();
    }
    //导出
    @AutoLog(value = "车辆加油记录导出-excel表格")
    @ApiOperation(value = "车辆加油记录导出excel表格", notes = "车辆加油记录—导出excel表格")
    @GetMapping(value = "/exportTable")
    // ModelAndView 导出表格流
    public ModelAndView exportTable() {
        VeOaCarJiayouTableVo veOaCarJiayouTableVo =new VeOaCarJiayouTableVo();
    // 创建导出流
        ModelAndView mv = new ModelAndView(new JeecgEntityExcelView());
        // 查数据获得加油表格的集合
        List<VeOaCarJiayouExportVo> list = iVeOaCarJiayouService.xporte(veOaCarJiayouTableVo);
        // 文件的文件名
        mv.addObject(NormalExcelConstants.FILE_NAME, "车辆加油记录");
        // 数据的类型
        mv.addObject(NormalExcelConstants.CLASS, VeOaCarJiayouExportVo.class);
        // 获取redis存的用户值

        LoginUser user = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        // ExportParams  Export工具类   （参数1--》title:表格标题  参数2--》secomdTitle:第二行的标题，  参数3--》secomdTitle:最下面尾部的信息）
        ExportParams exportParams = new ExportParams("车辆加油记录", "导出人:" + user.getRealname(), "导出车辆加油记录");
        mv.addObject(NormalExcelConstants.PARAMS, exportParams);
            mv.addObject(NormalExcelConstants.DATA_LIST, list);


        return mv;
    }
    //单个导出
    @AutoLog(value = "车辆加油记录导出-单个导出excel表格")
    @ApiOperation(value = "单个导出excel表格", notes = "车辆加油记录—单个导出导出excel表格")
    @GetMapping(value = "/exportTableOne")
    // ModelAndView 导出表格流
    public ModelAndView exportTableOne() {
        VeOaCarJiayouTableVo veOaCarJiayouTableVo =new VeOaCarJiayouTableVo();
        VeOaCarInfoTableVo vo = (VeOaCarInfoTableVo) redisUtil.get("carInfo");

        veOaCarJiayouTableVo.setCarId(vo.getId().intValue() );
        System.out.println(veOaCarJiayouTableVo);
        // 创建导出流
        ModelAndView mv = new ModelAndView(new JeecgEntityExcelView());
        // 查数据获得加油表格的集合
        List<VeOaCarJiayouExportVo> list = iVeOaCarJiayouService.xporte(veOaCarJiayouTableVo);
        // 文件的文件名
        mv.addObject(NormalExcelConstants.FILE_NAME, "车辆加油记录");
        // 数据的类型
        mv.addObject(NormalExcelConstants.CLASS, VeOaCarJiayouExportVo.class);
        // 获取redis存的用户值

        LoginUser user = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        // ExportParams  Export工具类   （参数1--》title:表格标题  参数2--》secomdTitle:第二行的标题，  参数3--》secomdTitle:最下面尾部的信息）
        ExportParams exportParams = new ExportParams("车辆加油记录", "导出人:" + user.getRealname(), "导出车辆加油记录");
        mv.addObject(NormalExcelConstants.PARAMS, exportParams);
        mv.addObject(NormalExcelConstants.DATA_LIST, list);


        return mv;
    }
    //导入
    @AutoLog(value = "车辆加油记录-导入excel表格")
    @ApiOperation(value = "导入excel表格", notes = "车辆加油记录—导入excel表格")
    @PostMapping(value = "jiayouUploading")
    public Result<?> excelImport(HttpServletRequest req, HttpServletResponse resp) {
        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) req;
        Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
        for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
            MultipartFile file = entity.getValue();// 获取上传文件对象
            ImportParams params = new ImportParams();
            params.setTitleRows(2);
            params.setHeadRows(1);
            params.setNeedSave(true);
            try {
                List<VeOaCarJiayouExportVo> list = ExcelImportUtil.importExcel(file.getInputStream(), VeOaCarJiayouExportVo.class, params);
                // 获取redis存的用户值
                LoginUser user = (LoginUser) SecurityUtils.getSubject().getPrincipal();
                // 插入数据的集合
                List<VeOaCarJiayouEntity> entityList =new ArrayList<>();
                int count =list.size();
                for (VeOaCarJiayouExportVo jiayouExportVo:list){
                    if(jiayouExportVo.getCarName()==null||jiayouExportVo.getCarName().equals("")){
                        count--;
                        continue;
                    }
                    VeOaCarJiayouEntity veOaCarJiayouEntity =new VeOaCarJiayouEntity();
                   VeOaCarInfoEntity veOaCarInfoEntity= iVeOaCarInfoService.getCarId(jiayouExportVo.getCarName());
                    if(veOaCarInfoEntity!=null){
                        veOaCarJiayouEntity.setCarId(veOaCarInfoEntity.getId());

                    }else{
                        return Result.error("文件导入失败: 车辆输入错误  没有这辆车！" );
                    }
                    veOaCarJiayouEntity.setCarName(jiayouExportVo.getCarName());
                    // 字符串转换成时间类型
                    SimpleDateFormat formatter=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                    Date date=formatter.parse(jiayouExportVo.getJiayouDate());
                    veOaCarJiayouEntity.setJiayouDate(date);
                    veOaCarJiayouEntity.setJingbanUser(jiayouExportVo.getJingbanUser());
                    veOaCarJiayouEntity.setDriverUser(jiayouExportVo.getDriverUser());
                    veOaCarJiayouEntity.setJiayouAddress(jiayouExportVo.getJiayouAddress());
                    veOaCarJiayouEntity.setStartFuel(jiayouExportVo.getStartFuel());
                    veOaCarJiayouEntity.setAfterFuel(jiayouExportVo.getAfterFuel());
                    veOaCarJiayouEntity.setFuelConsumption(jiayouExportVo.getFuelConsumption());
                    veOaCarJiayouEntity.setPrice(jiayouExportVo.getPrice());
                    veOaCarJiayouEntity.setTotalPrice(jiayouExportVo.getTotalPrice());
                    veOaCarJiayouEntity.setBackInfo(jiayouExportVo.getBackInfo());
                    veOaCarJiayouEntity.setCreateBy(user.getId());
                    veOaCarJiayouEntity.setUpdateBy(user.getId());
                    veOaCarJiayouEntity.setTerminalId(1);
                    veOaCarJiayouEntity.setCreateByName(user.getRealname());
                    veOaCarJiayouEntity.setUpdateByName(user.getRealname());

                    entityList.add(veOaCarJiayouEntity);
                }
                //update-begin-author:taoyan date:20190528 for:批量插入数据
                long start = System.currentTimeMillis();
                iVeOaCarJiayouService.saveBatch(entityList);
                //400条 saveBatch消耗时间1592毫秒  循环插入消耗时间1947毫秒
                //1200条  saveBatch消耗时间3687毫秒 循环插入消耗时间5212毫秒
//                log.info("消耗时间" + (System.currentTimeMillis() - start) + "毫秒");
                //update-end-author:taoyan date:20190528 for:批量插入数据
                return Result.ok("文件导入成功！数据行数：" + count);
            } catch (Exception e) {
//                log.error(e.getMessage(), e);
                return Result.error("文件导入失败:" + e.getMessage());
            } finally {
                try {
                    file.getInputStream().close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return Result.error("文件导入失败！");
//        return super.importExcel(req, resp, VeOaCarJiayouEntity.class);
    }
    //单个导入
    @AutoLog(value = "车辆加油记录-导入excel表格")
    @ApiOperation(value = "导入excel表格", notes = "车辆加油记录—导入excel表格")
    @PostMapping(value = "jiayouUploadingOne")
    public Result<?> jiayouUploadingOne(HttpServletRequest req, HttpServletResponse resp) {
        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) req;
        Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();

        // 判断这辆车的导入
        VeOaCarInfoTableVo vo = (VeOaCarInfoTableVo) redisUtil.get("carInfo");
        System.out.println( vo);

        for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
            MultipartFile file = entity.getValue();// 获取上传文件对象
            ImportParams params = new ImportParams();
            params.setTitleRows(2);
            params.setHeadRows(1);
            params.setNeedSave(true);
            try {
                List<VeOaCarJiayouExportVo> list = ExcelImportUtil.importExcel(file.getInputStream(), VeOaCarJiayouExportVo.class, params);
                // 获取redis存的用户值
                LoginUser user = (LoginUser) SecurityUtils.getSubject().getPrincipal();
                // 插入数据的集合
                List<VeOaCarJiayouEntity> entityList =new ArrayList<>();
                int count =list.size();
                for (VeOaCarJiayouExportVo jiayouExportVo:list){
                    if(jiayouExportVo.getCarName()==null||jiayouExportVo.getCarName().equals("")){
                        count--;
                        continue;
                    }
                    VeOaCarJiayouEntity veOaCarJiayouEntity =new VeOaCarJiayouEntity();
                    VeOaCarInfoEntity veOaCarInfoEntity= iVeOaCarInfoService.getCarId(vo.getCarName());
                    // 判断只能导入该车辆
                    if(vo.getCarName().equals(jiayouExportVo.getCarName())){


                    }else{
                        return Result.error("文件导入失败: 只能导入《"+veOaCarInfoEntity.getCarName()+"》车辆" );

                    }

                    veOaCarJiayouEntity.setCarName(jiayouExportVo.getCarName());
                    // 字符串转换成时间类型
                    SimpleDateFormat formatter=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                    Date date=formatter.parse(jiayouExportVo.getJiayouDate());
                    veOaCarJiayouEntity.setJiayouDate(date);
                    veOaCarJiayouEntity.setCarId(veOaCarInfoEntity.getId());
                    veOaCarJiayouEntity.setJingbanUser(jiayouExportVo.getJingbanUser());
                    veOaCarJiayouEntity.setDriverUser(jiayouExportVo.getDriverUser());
                    veOaCarJiayouEntity.setJiayouAddress(jiayouExportVo.getJiayouAddress());
                    veOaCarJiayouEntity.setStartFuel(jiayouExportVo.getStartFuel());
                    veOaCarJiayouEntity.setAfterFuel(jiayouExportVo.getAfterFuel());
                    veOaCarJiayouEntity.setFuelConsumption(jiayouExportVo.getFuelConsumption());
                    veOaCarJiayouEntity.setPrice(jiayouExportVo.getPrice());
                    veOaCarJiayouEntity.setTotalPrice(jiayouExportVo.getTotalPrice());
                    veOaCarJiayouEntity.setBackInfo(jiayouExportVo.getBackInfo());
                    veOaCarJiayouEntity.setCreateBy(user.getId());
                    veOaCarJiayouEntity.setUpdateBy(user.getId());
                    veOaCarJiayouEntity.setTerminalId(1);
                    veOaCarJiayouEntity.setCreateByName(user.getRealname());
                    veOaCarJiayouEntity.setUpdateByName(user.getRealname());

                    entityList.add(veOaCarJiayouEntity);
                }
                //update-begin-author:taoyan date:20190528 for:批量插入数据
                long start = System.currentTimeMillis();
                iVeOaCarJiayouService.saveBatch(entityList);
                //400条 saveBatch消耗时间1592毫秒  循环插入消耗时间1947毫秒
                //1200条  saveBatch消耗时间3687毫秒 循环插入消耗时间5212毫秒
//                log.info("消耗时间" + (System.currentTimeMillis() - start) + "毫秒");
                //update-end-author:taoyan date:20190528 for:批量插入数据
                return Result.ok("文件导入成功！数据行数：" + count);
            } catch (Exception e) {
//                log.error(e.getMessage(), e);
                return Result.error("文件导入失败:" + e.getMessage());
            } finally {
                try {
                    file.getInputStream().close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return Result.error("文件导入失败！");
//        return super.importExcel(req, resp, VeOaCarJiayouEntity.class);
    }

    //导出excel模板
    @AutoLog(value = "导出excel模板")
    @ApiOperation(value = "导出excel模板", notes = "车辆加油—导出excel模板")
    @GetMapping(value = "exportModel")
    public ModelAndView exportModel() {
        // 创建导出流

        ModelAndView mv = new ModelAndView(new JeecgEntityExcelView());
        // 文件的文件名

        mv.addObject(NormalExcelConstants.FILE_NAME, "车辆加油记录");
        mv.addObject(NormalExcelConstants.CLASS, VeOaCarJiayouExportVo.class);
        // 获取redis存的用户值

        LoginUser user = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        // ExportParams  Export工具类   （参数1--》title:表格标题  参数2--》secomdTitle:第二行的标题，  参数3--》secomdTitle:最下面尾部的信息）

        ExportParams exportParams = new ExportParams("车辆加油记录", "导出人:" + user.getRealname(), "导出车辆加油记录");

        mv.addObject(NormalExcelConstants.PARAMS, exportParams);
        mv.addObject(NormalExcelConstants.DATA_LIST, new ArrayList<VeOaCarJiayouExportVo>());
        return mv;
    }
    // 增加加油记录
    @AutoLog(value = "车辆加油记录-增加加油记录")
    @ApiOperation(value="增加加油记录", notes="车辆加油记录-增加加油记录")
    @PostMapping(value = "/addCarRefueRecord")
    public Result addCarRefueRecord(VeOaCarJiayouEntity veOaCarJiayouEntity,String jiayouDateStr) throws ParseException {
        // 获取redis存的用户值
        LoginUser user = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        // 把用户的值存进数据库
        veOaCarJiayouEntity.setCreateBy(user.getId());
        veOaCarJiayouEntity.setUpdateBy(user.getId());
        veOaCarJiayouEntity.setCreateByName(user.getRealname());
        veOaCarJiayouEntity.setUpdateByName(user.getRealname());

        veOaCarJiayouEntity.setCarName( iVeOaCarInfoService.getCarName(veOaCarJiayouEntity.getCarId()).getCarName());
    // 前端传过来的时间字符串转换成日期
        SimpleDateFormat formatter=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

        Date date=formatter.parse(jiayouDateStr.trim());
        veOaCarJiayouEntity.setJiayouDate(date);
       Integer result= iVeOaCarJiayouService.addFuelManager(veOaCarJiayouEntity);
        return Result.OK(result);
    }

    // 详情展示
    @AutoLog(value = "车辆加油记录-增加加油记录")
    @ApiOperation(value="增加加油记录", notes="车辆加油记录-增加加油记录")
    @PostMapping(value = "/viewDetails")
    public Result viewDetails(Integer id) {
        VeOaCarJiayouShowVo veOaCarJiayouShowVo= iVeOaCarJiayouService.showFuelManager(id);
        return Result.OK(veOaCarJiayouShowVo);
    }

    // 获取车辆姓名下拉框
    @AutoLog(value = "车辆加油记录-车辆姓名下拉框")
    @ApiOperation(value="车辆姓名下拉框", notes="车辆加油记录-车辆姓名下拉框")
    @PostMapping(value = "/getCarBox")
    public Result getCarBox() {
        return Result.OK(iVeOaCarInfoService.getCarBox());
    }

    // 修改加油记录
    @AutoLog(value = "车辆加油记录-修改加油记录")
    @ApiOperation(value="修改加油记录", notes="车辆加油记录-修改加油记录")
    @PostMapping(value = "/amendFefuelMessage")
    public Result amendFefuelMessage(VeOaCarJiayouEntity veOaCarJiayouEntity,String jiayouDateStr) throws ParseException {

        // 前端传过来的时间字符串转换成日期
        SimpleDateFormat formatter=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date date=formatter.parse(jiayouDateStr.trim());
        veOaCarJiayouEntity.setJiayouDate(date);
        veOaCarJiayouEntity.setCarName( iVeOaCarInfoService.getCarName(veOaCarJiayouEntity.getCarId()).getCarName());

        Integer result= iVeOaCarJiayouService.amendFuelManager(veOaCarJiayouEntity);
        return Result.OK(result);
    }
    // 高级搜索
    @AutoLog(value = "车辆加油记录-高级搜索")
    @ApiOperation(value="高级搜索", notes="车辆加油记录-高级搜索")
    @PostMapping(value = "/advancedQuery")

    public Result advancedQuery(@RequestBody String queryArray) {
        Map<String, List<QueryCondition>> maps = (Map<String, List<QueryCondition>>) JSON.parse(queryArray);
        List<QueryCondition> list=new ArrayList<QueryCondition>(JSONArray.parseArray(maps.get("queryArray").toString(),QueryCondition.class));
       String  conditionStr =  QueryConditionTool.getQueryConditionTool().advancedQuery(list);

        HashMap<String , Object>  map=null;
            map= iVeOaCarJiayouService.advancedQuery(conditionStr);

        return  Result.OK(map);
    }

    @AutoLog(value = "车辆加油记录-模板地址获取")
    @ApiOperation(value = "模板地址", notes = "车辆加油记录-模板地址获取")
    @PostMapping(value = "/getUrl")
    public Result<T> getUrl() throws Exception {
        Result result = new Result();
        String url= OssDownloadUtil.getOssDownloadUtil().downFileFromOSS("车辆加油记录模板.xls");
        result.success(url);
        return result;
    }
}
